<?php

namespace App\Console\Commands;

use App\Models\ProjectUsers;
use App\Project;
use App\ProjectUsersLog;
use Carbon\Carbon;
use Carbon\CarbonPeriod;
use GuzzleHttp\Client;
use Illuminate\Console\Command;

class Wechat extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'wechat:push';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '推送今日还没有读经的弟兄姐妹';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();

    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $porject = Project::where('id',1)->first();
        $project_users = ProjectUsersLog::where('date', date('Y-m-d'))->get();

        $project_user_ids = $project_users->pluck('user_id');

        $users =  ProjectUsers::whereNotIn('id',$project_user_ids)->where('project_id',1)->where('status',1)->get();
        if($users->count()>0){
            foreach($users as $user){
                $real_names[] =  $user->real_name;
            }

            $message = '亲爱的弟兄姐妹【 ' . implode(',',$real_names) . '】由于您参加了 ['.$porject->name.']，经过系统检测到您今日'. date('Y-m-d') .'还没有进行打卡，如忘记打卡或者还没有读经，请按照计划读经，完成后回复[读经打卡]';
            $this->sendToGroup($message,$porject->wechat_group_id);
        }
        else{
            $message = '参与[' .$porject->name  . '] 的弟兄姐妹，全部完成了今日的计划';
            $this->sendToGroup($message,$porject->wechat_group_id);
        }


    }  


    public function sendToGroup($message, $group_id)
    {

        $client = new Client();

        $form_data['type'] = 100;
        $form_data['msg']  = urlencode($message);
        $form_data['to_wxid'] = $group_id;
        $form_data['robot_wxid'] = 'wxid_jb6ld4goptbm22';

        $form_data = array('data' => json_encode($form_data));
        
        $res =  $client->post('http://home.iceqi.club:1987/send', ['form_params' => $form_data]);

        return response()->json($res->getBody()->getContents());
    }
}
